<script>
export default {
  name: 'CarbonNeutralityPlan',
  props: {
    // 请求参数
    requestParams: {
      type: Object,
      default: () => ({})
    },
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  created() {
    this.loadingProjectList()
  },
  watch: {
    popData: {
      async handler(data) {
        if (data.id) {
          const param = Object.assign({}, data)
          param.effectiveTime = [param.effectiveTimeStart, param.effectiveTimeEnd]
          this.formData = param
        }
      },
      deep: true,
      immediate: true
    },
    confirm() {
      this.submit(true)
    }
  },
  methods: {
    async queryPlanCarbonNeutralityData() {
      if (this.formData.sceneProjectId != null && this.formData.sceneProjectId !== ''
        && this.formData.effectiveTime != null && this.formData.effectiveTime.length > 0) {
        const param = {
          sceneProjectId: this.formData.sceneProjectId,
          effectiveTimeStart: this.formData.effectiveTime[0],
          effectiveTimeEnd: this.formData.effectiveTime[1]
        }
        const res = await this.$api.carbonNeutralityPlan.queryPlanCarbonNeutrality(param)
        this.$set(this.formData, 'planCarbonNeutrality', res.data)
      }
    },
    async loadingProjectList() {
      const res = await this.$api.commonSelected({ code: 'SceneProjectSelected' })
      this.projectList = res.data
    },
    async saveAndNew() {
      await this.submit(false)
    },
    async existByRangeData() {
      const res = await this.$api.carbonNeutralityPlan.queryRangeDataExist({
        id: this.formData.id,
        sceneProjectId: this.formData.sceneProjectId,
        effectiveTimeStart: this.formData.effectiveTime[0],
        effectiveTimeEnd: this.formData.effectiveTime[1]
      })
      return res.data
    },
    async submit(closeDialog) {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          const body = Object.assign({}, this.formData)
          body.effectiveTimeStart = body.effectiveTime[0]
          body.effectiveTimeEnd = body.effectiveTime[1]
          delete body.effectiveTime
          const isAdd = body.id == null || body.id === ''
          if (isAdd) {
            delete body.id
          }
          const res = await this.$api.carbonNeutralityPlan[isAdd ? 'add' : 'update'](body)
          if (Number(res.code) === 1000) {
            this.$message.success(`${isAdd ? '新增' : '编辑'}成功！`)
            if (closeDialog) {
              this.$emit('onFinish', 'carbon-neutrality-plan-add')
            } else {
              this.formData = {}
            }
          }
        }
      })
    }
  },
  computed: {
    rules() {
      return {
        sceneProjectId: [{ required: true, message: '请选择项目' }],
        effectiveTime: [
          { required: true, message: '请选择生效时间' },
          {
            validator: async (rule, value, callback) => {
              if (this.formData.effectiveTime != null &&
                this.formData.effectiveTime.length > 0
                && this.formData.sceneProjectId) {
                const exist = await this.existByRangeData()
                if (exist) {
                  callback(`当前已设置生效时间范围：${this.formData.effectiveTime[0]}-${this.formData.effectiveTime[1]}不可重复设置已有时间范围`)
                } else {
                  callback()
                }
              }
            }
          }
        ],
        planCarbonEmissions: [{ required: true, message: '请输入规划碳排' }],
        planCarbonZero: [{ required: true, message: '请输入规划零碳' }],
        planCarbonSequestration: [{ required: true, message: '请输入规划碳汇' }]
      }
    }
  },
  data() {
    return {
      loading: false,
      formData: {},
      projectList: []
    }
  }
}
</script>

<template>
  <div class="carbon-neutrality-plan-box">
    <el-form v-loading="loading"
             ref="form"
             class="plan-form-top"
             :model="formData"
             :rules="rules"
             label-width="140px"
    >
      <el-form-item label="所属项目" prop="sceneProjectId">
        <el-select v-model="formData.sceneProjectId" placeholder="选择项目"
                   :disabled="this.formData.id != null">
          <el-option v-for="item in projectList" :key="item.value" :value="item.value" :label="item.label"
                     @change="queryPlanCarbonNeutralityData"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生效时间范围" prop="effectiveTime">
        <el-date-picker v-model="formData.effectiveTime" type="daterange" value-format="yyyy-MM-dd" format="yyyy-MM-dd"
                        range-separator="至"
                        style="width: 60%" @change="queryPlanCarbonNeutralityData"></el-date-picker>
      </el-form-item>
      <el-form-item label="规划碳排(kgCO2)" prop="planCarbonEmissions">
        <el-input-number v-model="formData.planCarbonEmissions" style="width: 60%" />

      </el-form-item>
      <el-form-item label="规划碳减(kgCO2)" prop="planCarbonZero">
        <el-input-number v-model="formData.planCarbonZero" style="width: 60%" />

      </el-form-item>
      <el-form-item label="规划碳汇(kgCO2)" prop="planCarbonSequestration">
        <el-input-number v-model="formData.planCarbonSequestration" style="width: 60%"/>
      </el-form-item>
      <el-form-item label="规划碳中和(kgCO2)" prop="planCarbonNeutrality">
        <el-input v-model="formData.planCarbonNeutrality" :disabled="true" style="width: 60%" />
      </el-form-item>
    </el-form>
    <el-row style="display: flex;justify-content: right">
      <el-button type="text" @click="saveAndNew">保存并继续新增下一条</el-button>
    </el-row>
  </div>
</template>
